import React, { useState, useEffect } from "react";
import { PageContainer, ProTable } from "@ant-design/pro-components";
import { Button, Tooltip, Space, Input, Select, message } from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  FilterOutlined,
  ExportOutlined,
  LoadingOutlined,
  FileExcelOutlined,
  UploadOutlined,
} from "@ant-design/icons";
import * as XLSX from "xlsx";

import { Product } from "wasp/entities";
import { getProducts, useQuery } from "wasp/client/operations";

export const Sub: React.FC = () => {
  const {
    data: queryProducts,
    isLoading: isQueryLoading,
    error,
  } = useQuery(getProducts);

  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(false);
  const [filter, setFilter] = useState<string>("全部");
  const [exporting, setExporting] = useState(false);

  // 初始化加载状态
  useEffect(() => {
    setLoading(true);
  }, []);

  // 处理查询结果
  useEffect(() => {
    if (error) {
      message.error(`获取产品数据失败: ${error.message}`);
      setLoading(isQueryLoading);
      return;
    }

    if (queryProducts) {
      setProducts(queryProducts);
      setLoading(isQueryLoading);
    }
  }, [queryProducts, error]);

  // 模拟删除产品
  const handleDelete = (id: number) => {
    setProducts(products.filter((product) => product.id !== id));
  };

  // 筛选产品
  const handleFilterChange = (value: string) => {
    setFilter(value);
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 500);
  };

  // 根据筛选条件获取产品
  const filteredProducts =
    filter === "全部"
      ? products
      : products.filter((product) => product.category === filter);

  // 导出Excel文件
  const exportToExcel = () => {
    setExporting(true);

    try {
      // 准备导出数据
      const exportData = filteredProducts.map((product) => ({
        ID: product.id,
        产品名称: product.name,
        分类: product.category,
        "价格(元)": `¥${product.price}`,
        库存: product.stock,
        状态: product.status,
      }));

      // 创建工作簿和工作表
      const ws = XLSX.utils.json_to_sheet(exportData);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "产品列表");

      // 生成Excel文件并下载
      const excelBuffer = XLSX.write(wb, { bookType: "xlsx", type: "array" });
      const blob = new Blob([excelBuffer], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });

      // 创建下载链接
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `产品列表_${new Date().toISOString().slice(0, 10)}.xlsx`;
      a.click();

      // 释放URL对象
      URL.revokeObjectURL(url);

      message.success("导出成功！");
    } catch (error) {
      console.error("导出失败:", error);
      message.error("导出失败，请重试！");
    } finally {
      setExporting(false);
    }
  };

  // 下载Excel模板
  const downloadTemplate = () => {
    try {
      // 模板文件路径 (假设在public/templates目录下)
      const templateUrl = "/templates/product_template.xlsx";

      // 创建下载链接
      const a = document.createElement("a");
      a.href = templateUrl;
      a.download = "product_template.xlsx";
      a.click();

      message.success("模板下载成功！");
    } catch (error) {
      console.error("模板下载失败:", error);
      message.error("模板下载失败，请重试！");
    }
  };

  // 列定义
  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      width: 80,
    },
    {
      title: "产品名称",
      dataIndex: "name",
      width: 200,
    },
    {
      title: "分类",
      dataIndex: "category",
      width: 120,
    },
    {
      title: "价格(元)",
      dataIndex: "price",
      width: 100,
      render: (text: number) => `¥${text}`,
    },
    {
      title: "库存",
      dataIndex: "stock",
      width: 80,
    },
    {
      title: "状态",
      dataIndex: "status",
      width: 100,
      valueEnum: {
        在售: { text: "在售", status: "Success" },
        缺货: { text: "缺货", status: "Error" },
      },
    },
    {
      title: "操作",
      valueType: "option",
      width: 120,
      render: (_: unknown, record: { id: number }) => [
        <Tooltip title="编辑">
          <Button icon={<EditOutlined />} size="middle" />
        </Tooltip>,
        <Tooltip title="删除">
          <Button
            icon={<DeleteOutlined />}
            size="middle"
            danger
            onClick={() => handleDelete(record.id)}
          />
        </Tooltip>,
      ],
    },
  ];

  return (
    <PageContainer>
      <div
        style={{
          marginBottom: 16,
          display: "flex",
          justifyContent: "space-between",
        }}
      >
        <div>
          <Button icon={<PlusOutlined />} type="primary">
            添加产品
          </Button>
          <Button
            icon={<FileExcelOutlined />}
            style={{ marginLeft: 8 }}
            onClick={downloadTemplate}
          >
            下载模板
          </Button>
          <Button
            icon={<UploadOutlined />}
            style={{ marginLeft: 8 }}
            onClick={downloadTemplate}
          >
            上传数据
          </Button>
          <Button
            icon={exporting ? <LoadingOutlined spin /> : <ExportOutlined />}
            style={{ marginLeft: 8 }}
            onClick={exportToExcel}
            disabled={
              exporting || !filteredProducts || filteredProducts.length === 0
            }
          >
            {exporting ? "导出中..." : "导出数据"}
          </Button>
        </div>

        <div style={{ display: "flex", gap: 8 }}>
          <Select
            value={filter}
            onChange={handleFilterChange}
            style={{ width: 120 }}
          >
            <Select.Option value="全部">全部</Select.Option>
            <Select.Option value="电子产品">电子产品</Select.Option>
            <Select.Option value="家具">家具</Select.Option>
            <Select.Option value="日用品">日用品</Select.Option>
          </Select>
          <Space>
            <Input.Search placeholder="搜索产品" style={{ width: 200 }} />
            <Button icon={<FilterOutlined />}>高级筛选</Button>
          </Space>
        </div>
      </div>

      <ProTable
        columns={columns as any}
        dataSource={filteredProducts}
        loading={loading}
        rowKey="id"
        rowSelection={{
          type: "checkbox",
        }}
        search={false}
        pagination={{
          pageSize: 10,
          total: filteredProducts ? filteredProducts.length : 0,
        }}
        actionRef={React.createRef()}
      />
    </PageContainer>
  );
};
